package com.djf.word.listener;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.djf.word.entity.Order;
import com.djf.word.entity.OrderExcelProgress;
import com.djf.word.service.OrderService;

import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author 26393
 * @Date 2025/7/9 18:31
 * @Version 1.0
 */
public class OrderExportExcelHandler {
    private final OrderService orderService;
    private final ConcurrentHashMap<String, OrderExcelProgress> progressMap;
    private final int pageSize = 1000;

    public OrderExportExcelHandler(OrderService orderService, ConcurrentHashMap<String, OrderExcelProgress> progressMap) {
        this.orderService = orderService;
        this.progressMap = progressMap;
    }

    public void export(OutputStream os, OrderExcelProgress progress, String progressId) {
        int pageNum = 1;
        boolean hasNext = true;
        int totalCount = Math.toIntExact(orderService.count());
        int rowCount = 0;
        progress.setStartTime(System.currentTimeMillis());

        ExcelWriterBuilder writerBuilder = EasyExcel.write(os, Order.class);
        try (
                ExcelWriter writer = writerBuilder.build()
        )
        {
            WriteSheet sheet = EasyExcel.writerSheet("订单数据").build();
            while (hasNext) {
                Page<Order> page = orderService.page(new Page<>(pageNum, pageSize));
                List<Order> records = page.getRecords();
                if (records.isEmpty()) break;
                writer.write(records, sheet);

                rowCount += records.size();
                double percent = totalCount > 0 ? rowCount * 1.0 / totalCount : 1.0;
                long now = System.currentTimeMillis();
                long elapsed = now - progress.getStartTime();
                long estimatedTotal = (long) (elapsed / (percent > 0 ? percent : 1));
                long estimatedLeft = estimatedTotal - elapsed;
                progress.setProgress(Math.min(percent, 1.0));
                progress.setEstimatedSecondsLeft(Math.max(estimatedLeft / 1000, 0));
                progress.setMessage("导出第" + rowCount + "条/共" + totalCount + "条");
                progress.setLastUpdateTime(now);
                progressMap.put(progressId, progress);

                pageNum++;
                hasNext = records.size() == pageSize;
            }
            progress.setProgress(1.0);
            progress.setMessage("导出完成");
            progress.setEstimatedSecondsLeft(0);
            progress.setLastUpdateTime(System.currentTimeMillis());
            progressMap.put(progressId, progress);
        }
    }
}
